// index.js
const app = getApp();
const audioCtx = wx.createInnerAudioContext();

Page({
  data: {
    item: 0,
    tab: 0,
    state: "paused", // 播放状态，初始为暂停
    playIndex: 0,
    play: {
      currentTime: '00:00',
      duration: '00:00',
      percent: 0,
      title: '',
      singer: '',
      coverImgUrl: '',
      musicUrl: '', // 音乐文件的URL
    },
  },

  onLoad: function(options) {
    const id = options.id; // 从页面参数中获取id
    this.fetchMusicData(id);
  },

  onUnload: function() {
    audioCtx.stop(); // 页面卸载时停止音乐播放
  },

  onHide: function() {
    audioCtx.stop(); // 页面隐藏时也停止音乐播放
  },

  fetchMusicData: function(id) {
    // 根据ID请求后端接口
    wx.request({
      url: `http://10.10.18.137:8888/sfzy/fm/selectById?id=${id}`,
      method: 'GET',
      success: (res) => {
        if (res.data.status === 200) {
          const data = res.data.data;
          this.setData({
            'play.title': data.name,
            'play.musicUrl': `http://10.10.18.137:8888/sfzy/downLoad?filename=${data.music}`, // 音乐文件的完整URL
            'play.coverImgUrl': `http://10.10.18.137:8888/sfzy/downLoad?filename=${data.img}` // 封面图像的完整URL
          });
          this.setMusic();
        } else {
          wx.showToast({ title: '获取音乐信息失败', icon: 'none' });
        }
      },
      fail: () => {
        wx.showToast({ title: '请求失败', icon: 'none' });
      }
    });
  },

  setMusic: function() {
    audioCtx.src = this.data.play.musicUrl; // 设置音乐文件路径
    audioCtx.play(); // 开始播放
    this.setData({ state: "running" });

    // 只绑定一次监听播放进度和播放结束事件
    audioCtx.offTimeUpdate(); // 先取消上一次的监听，避免多次绑定
    audioCtx.onTimeUpdate(() => {
      const currentTime = audioCtx.currentTime;
      const duration = audioCtx.duration;

      this.setData({
        'play.currentTime': this.formatTime(currentTime),
        'play.duration': this.formatTime(duration),
        'play.percent': (currentTime / duration) * 100,
      });
    });

    // 播放结束时的处理
    audioCtx.offEnded(); // 取消之前的结束事件监听
    audioCtx.onEnded(() => {
      this.setData({ state: "paused" });
    });
  },

  formatTime: function(time) {
    const minute = Math.floor(time / 60);
    const second = Math.floor(time % 60);
    return `${minute < 10 ? '0' : ''}${minute}:${second < 10 ? '0' : ''}${second}`;
  },

  play: function() {
    audioCtx.play();
    this.setData({ state: "running" });
  },

  pause: function() {
    audioCtx.pause();
    this.setData({ state: "paused" });
  },

  togglePlayPause: function() {
    if (this.data.state === "running") {
      this.pause();
    } else {
      this.play();
    }
  }
});
